//
//  HGLoopView.swift
//  imageCarouselView
//
//  Created by day-day-Smile on 2018/5/30.
//  Copyright © 2018年 SmileHg. All rights reserved.
//

import UIKit

private let cellId = "cellId"
class HGLoopView: UICollectionView,UICollectionViewDataSource,UICollectionViewDelegate {
    
    var urls = [Any]()
   
    init(url:[Any]) {
        super.init(frame: CGRect.zero, collectionViewLayout: HGFlowLayout.init())
        urls = url
        self.dataSource = self
        self.delegate = self
        
        self.register(HGLoopViewCell.self, forCellWithReuseIdentifier: cellId)
        
        
        /// 初始显示第二组 【0，1，2】【3，（）4，5】
        /// 在主队列异步，保证数据源方法执行完毕后，在滚动collectionView
        /// 安排任务在主线程执行
        /// 如果主线程当前有任务，主队列暂时不调用任务
        DispatchQueue.main.async {
            let indexPath = IndexPath(item: self.urls.count, section: 0)
            
            self.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition.left, animated: false)
            
        }
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.urls.count * 100
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! HGLoopViewCell
        cell.backgroundColor = UIColor(red: CGFloat(arc4random() % 255) / 255.0, green: CGFloat(arc4random() % 255) / 255.0, blue: CGFloat(arc4random() % 255) / 255.0, alpha: 1.0)
        cell.urlModel = self.urls[indexPath.row % self.urls.count] as? URL
        return cell
    }
    

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        /// 1.获取当前停止的界面
        var offSet = scrollView.contentOffset.x / scrollView.bounds.size.width
        
        /// 2.第0页，调转到，第二组的第0 页
        /// 最后一页，跳转到第0组的最后一页
        if offSet == 0 || offSet == CGFloat(self.numberOfItems(inSection: 0) - 1) {
            print(offSet)
            if offSet == 0{
                offSet = CGFloat(self.urls.count)
            }else{
                offSet = CGFloat(self.urls.count - 1)
            }
        }
        
        /// 3.重新调整contentOffset
        scrollView.contentOffset = CGPoint(x: offSet * scrollView.bounds.size.width, y: 0)
    }
    
}
